package cn.cvs.redis1demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class NewController {
    @Autowired
    RedisTemplate redisTemplate;
    //更新浏览量
    @GetMapping("/detail/{id}")
    public String see(@PathVariable Integer id, Model model){

        //阅读量自增1
        redisTemplate.opsForHash().increment("new_" + id, "read", 1);
        //查询出数据放到model中，方便前端页面展示点赞量和阅读量
        Map map = redisTemplate.opsForHash().entries("new_" + id);
        model.addAllAttributes(map);

        return "new"+id;
    }

    @GetMapping("/addZan/{id}/{opType}")
    @ResponseBody
    public Long addZan(@PathVariable Integer id,@PathVariable Integer opType){
        Long countZan;
        if (opType==1){
            countZan = redisTemplate.opsForHash().increment("new_" + id, "countZan", 1);
        }else {
            countZan=redisTemplate.opsForHash().increment("new_"+id,"countZan",-1);
        }
        return countZan;
    }
}
